import { request } from "@xiaoe/js-tools/lib/request";

function addCoupon(params) {
    return new Promise((resolve, reject) => {
        request({
            url: `/xe.csg.coupon.resource.price.receive/1.0.0`,
            responseType: 'json',
            requestType:'json',
            params,
            pack: null
        })
            .then((res) => {
                if (res.code === 0) {
                    console.log(res.msg);
                    resolve()
                } else {
                    reject()
                    // TODO
                    // throw new Error("优惠券批量领取报错", res.msg);
                    console.log("优惠券批量领取报错", res.msg);
                }
            })
            .catch((err) => {
                reject()
                throw new Error("优惠券批量领取报错");
            });
    })
}

export function postCouponList(params) {
    console.log('123request',request);
    return new Promise((resolve, reject) => {
        request({
            url: `/xe.csg.coupon.resource.price/1.0.0`,
            params,
            pack: '',
            requestType:'json'
        })
            .then((res) => {
                if (res.code === 0) {
                    const { display_deduct_price, deduct_total, deduct_need_receive_coupon_ids} = res.data;
                    if (display_deduct_price && deduct_total) {
                        // 设置券后价
                        // 设置需要领取的优惠券
                        console.log('是否是数组', deduct_need_receive_coupon_ids)
                        if (typeof deduct_need_receive_coupon_ids === 'object' && deduct_need_receive_coupon_ids.length !== 0 ) {
                            let coupon_ids = Object.keys(deduct_need_receive_coupon_ids).map(key => ({
                                id: key,
                                count: deduct_need_receive_coupon_ids[key]
                            }));
                            addCoupon({ coupons: coupon_ids }).then(()=>{
                                resolve({needDoValuate:true})
                            }).catch(()=>{
                                resolve(res.data);
                            })
                        }else{
                            resolve(res.data);
                        }
                    }else{
                        resolve(res.data);
                    }
                } else {
                    resolve(res.data);
                    throw new Error("优惠券获取列表报错或者没有可领券", res.msg);
                }
            })
            .catch((err) => {
                resolve();
                throw new Error("优惠券获取列表报错或者没有可领券");
            });
    });
}
